const timerObj = {
    id: 1000,
    getId: () => {
        timerObj.id++
        return timerObj.id
    },
    timer: null as any,
    map: new Map<number, { endTime: number; fun: () => void; id: number }>(),
    add: (fun: () => void, endTime: number) => {
        const id = timerObj.getId()
        timerObj.map.set(id, {
            endTime: new Date().getTime() + endTime,
            fun,
            id
        })
        return id
    },
    remove: (id: number) => {
        timerObj.map.delete(id)
    }
}

export default class Timer {
    static init() {
        timerObj.timer = setInterval(() => {
            const thisTime = new Date().getTime()
            timerObj.map.forEach((el) => {
                if (thisTime - el.endTime > 0) {
                    el.fun()
                    timerObj.remove(el.id)
                }
            })
        }, 1)
    }

    /**
     * 添加一个延时任务
     * @param fun
     * @param endTime
     */
    static once(fun: () => void, endTime: number): number {
        if (timerObj.timer == null) this.init()
        return timerObj.add(fun, endTime)
    }

    /**
     * 移除任务
     * @param id
     */
    static unOnce = (id: number) => {
        timerObj.map.delete(id)
    }

    /**
     * 清空任务
     */
    static clear = () => {
        timerObj.map.clear()
    }

    static delay = (time: number) => {
        return new Promise((resolve) => {
            Timer.once(() => {
                resolve(true)
            }, time)
        })
    }

    /**
        循环执行
     */
    static on = (callback: Function, time: number, runOne: boolean = false): any => {
        let timer = setInterval(callback, time)
        if (runOne) callback()
        return timer
    }

    /**
        注销循环
     */
    static un(timer: any) {
        clearInterval(timer)
    }
}
